package com.codefish.codefish_blog.config.interceptors;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.codefish.codefish_blog.ajax.AjaxResult;
import com.codefish.codefish_blog.config.property.BlogWebProperties;
import com.codefish.codefish_blog.entity.User;
import com.codefish.codefish_blog.utils.JwtUtil;
import com.codefish.codefish_blog.utils.MapAndObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 文章点赞/评论等功能拦截器
 *
 * @author codefish
 * @version 1.0
 * @date 2022/04/11 上午 10:47
 */
@Slf4j
public class ArticleDataInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头字符串,格式为"Bearer xxx.yyy.zzz"
        String headerStr = request.getHeader("Authorization");
        //分割字符串
        String[] strs = headerStr.split(" ");
        //从请求头中获取schema和token
        String schema = strs[0];
        log.info("获得schema:{}", schema);
        String token = strs.length > 1 ? strs[1] : null;
        log.info("获得token:{}", token);
        //解析token(判断token是否有效以及是否过期)
        DecodedJWT decodedJWT = null;
        try {
            //验证schema是否为"Bearer"
            if (!"Bearer".equals(schema)) {
                throw new RuntimeException("schema片段不为\"Bearer\"");
            }
            //验证token
            decodedJWT = JwtUtil.verify(token);
        } catch (Exception e) {
            //token验证失败
            log.error("无效或伪造的token：{}", e.getMessage());
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            AjaxResult ajaxResult = AjaxResult.fail("权限不足");
            out.println(JSON.toJSONString(ajaxResult));
            out.flush();
            out.close();
            return false;
        }
        //token验证成功
        log.info("token验证成功,签发时间：{}", decodedJWT.getIssuedAt());
        log.info("过期时间：{}", decodedJWT.getExpiresAt());
        log.info("签名：{}", decodedJWT.getIssuer());
        //获取payload
        Map<String, Object> userInfo = decodedJWT.getClaim(BlogWebProperties.USER_INFO_PROPERTY).asMap();
        log.info("payload：{}", userInfo);
        //包装为user对象
        User user = MapAndObjectUtil.mapToObject(userInfo, User.class);
        //添加到request中
        request.setAttribute(BlogWebProperties.USER_INFO_PROPERTY, user);
        return true;
    }
}
